import { useState, useImperativeHandle } from 'react'
import { Modal, Form, Input, TreeSelect, message, Select, Radio, InputNumber } from 'antd'
import { getAllUserInfoAPI, addDeptAPI, editDeptAPI } from '../../api/deptListApi'

import { TypeAddMenuAPI, TypeEditMenuAPI, TypeMenuListAPI } from '../../type/api'
import { addMenuListAPI, editMenuListAPI } from '../../api/menuList'
interface Props {
  //父组件给的ref，我自子组件通过这个ref给父组件暴露方法
  mref: React.MutableRefObject<
    | {
        showModal: (type: string, data?: string | TypeMenuListAPI | TypeEditMenuAPI) => void
      }
    | undefined
  >
  //父组件给的获取菜单列表的方法
  getMenuListFn: () => void
  //父组件给的菜单列表数据

  menuList: TypeMenuListAPI[]
}

function CreateMenu(props: Props) {
  //存储父组件传来的添加编辑状态
  const [type, setType] = useState<string>('create')

  //获取表单实例
  const [form] = Form.useForm()
  //控制组件显示隐藏的状态
  const [isModalOpen, setIsModalOpen] = useState(false)
  //控制组件显示隐藏的方法(同时也暴露给父组件)
  const showModal = (type: string, data?: string | TypeMenuListAPI | TypeEditMenuAPI) => {
    resetForm()
    setIsModalOpen(true)

    if (Object.prototype.toString.call(data) === '[object Object]') {
      setType('edit')
      //这里通过给Form的Item设置初始值，就是表单value赋值，从而表单自动根据value显示label的值渲染
      form.setFieldsValue(
        // record.parentId, record.deptName, record.userName,_id
        data
      )
    } else {
      form.setFieldsValue(
        {
          parentId: data
        }
        // record.parentId, record.deptName, record.userName
      )
    }
  }
  //暴露给父组件的方法
  useImperativeHandle(props.mref, () => {
    return {
      // ... 你的方法 ...
      showModal
    }
  })
  // 控制组件提交方法
  const handleOk = async () => {
    const isOk = await form.validateFields()
    if (!isOk) {
      return
    }
    setIsModalOpen(false)
    if (type === 'create') {
      onFinish()
      message.success('添加成功')
    }
    if (type === 'edit') {
      await editMenuListAPI(form.getFieldsValue(true))
      message.success('编辑成功')
    }
    //重新获取菜单列表数据
    props.getMenuListFn()
  }

  //重置表单的方法
  function resetForm() {
    form.resetFields()
  }

  // 控制组件显示隐藏的方法
  const handleCancel = () => {
    setIsModalOpen(false)
  }

  //表单提交的方法
  function onFinish() {
    //获取表单数据
    const obj = form.getFieldsValue(true)

    //调用添加菜单的函数
    addMenuFn(obj)
  }

  //添加菜单的方法
  async function addMenuFn(obj: TypeAddMenuAPI) {
    await addMenuListAPI(obj)
  }

  return (
    <>
      <Modal title='创建菜单' open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Form
          name='basic'
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ menuState: 1, menuType: 1 }}
          onFinish={onFinish}
        >
          <Form.Item name='_id' hidden>
            <Input />
          </Form.Item>
          <Form.Item
            hasFeedback
            rules={[{ required: true, message: '必选项' }]}
            name='parentId'
            label='父级菜单'
          >
            <TreeSelect
              fieldNames={{
                label: 'menuName',
                value: '_id',
                children: 'children'
              }}
              style={{ width: '100%' }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              treeData={props.menuList}
              placeholder='点击选择父级菜单'
              treeDefaultExpandAll
            />
          </Form.Item>
          <Form.Item hasFeedback rules={[{ required: true, message: '必选项' }]} name='menuType'>
            <Radio.Group>
              <Radio.Button value={1}>菜单</Radio.Button>
              <Radio.Button value={2}>按钮</Radio.Button>
              <Radio.Button value={3}>页面</Radio.Button>
            </Radio.Group>
          </Form.Item>
          <Form.Item noStyle shouldUpdate>
            {() => {
              return form.getFieldValue('menuType') === 2 ? (
                <Form.Item
                  hasFeedback
                  rules={[{ required: true, message: '必选项' }]}
                  label='权限标识'
                  name='menuCode'
                >
                  <Input placeholder='请输入权限'></Input>
                </Form.Item>
              ) : (
                <>
                  <Form.Item
                    hasFeedback
                    rules={[{ required: true, message: '必选项' }]}
                    label='菜单名称'
                    name='menuName'
                  >
                    <Input placeholder='请输入菜单名称'></Input>
                  </Form.Item>
                  <Form.Item
                    hasFeedback
                    rules={[{ required: true, message: '必选项' }]}
                    label='菜单图标'
                    name='icon'
                  >
                    <Input placeholder='请输入菜单图标'></Input>
                  </Form.Item>
                </>
              )
            }}
          </Form.Item>
          <Form.Item
            hasFeedback
            rules={[{ required: true, message: '必选项' }]}
            name='path'
            label='路由地址'
          >
            <Input placeholder='请输入路由地址'></Input>
          </Form.Item>

          <Form.Item label='排序' name='orderBy' hasFeedback tooltip='排序值越大，优先级越高'>
            <InputNumber min={1} max={10} defaultValue={1} />;
          </Form.Item>
        </Form>
      </Modal>
    </>
  )
}

export default CreateMenu
